package com.zhuliwei.job;

import com.zhuliwei.constants.SystemConstants;
import com.zhuliwei.domain.entity.Article;
import com.zhuliwei.service.ArticleService;
import com.zhuliwei.utils.RedisCache;
import jakarta.annotation.Resource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 定时任务 每5分钟同步redis数据到Mysql
 *
 * @author 朱力维
 * @time 2022/10/19 18:17
 **/
@Component
public class ArticleJob {

    @Resource
    private ArticleService articleService;

    @Resource
    private RedisCache redisCache;

    @Scheduled(cron = "0 0/5 * * * ?")
    public void updateViewCount() {
        Map<String, Integer> viewCountMap = redisCache.getCacheMap(SystemConstants.VIEWCOUNT_MAP_PREFIX);
        List<Article> articles = articleService.list();
        articles.forEach(article -> {
            article.setViewCount(viewCountMap.get(article.getId()).longValue());
        });
        articleService.updateBatchById(articles);
    }

    @Scheduled(cron = "0 0/5 * * * ?")
    public void updateLikes() {
        List<Article> articles = articleService.list();
        articles.forEach(article -> {
            article.setLikes(redisCache.getCacheMapValue(SystemConstants.LIKES_MAP_PREFIX, article.getId()).toString());
        });
        articleService.updateBatchById(articles);
    }
}
